package cloud.xlh.my_system.paramresolver;

import cloud.xlh.domin.dto.UserDTO;
import cloud.xlh.infrastructure.utils.CommonUtil;
import cloud.xlh.infrastructure.utils.IpUtil;
import cloud.xlh.my_system.annotation.UserInfoParam;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/1/18 20:19
 * @ Description: 用户信息解析器 注册用途
 */
@Component
public class UserInfoParamResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserDTO.class) && parameter.hasParameterAnnotation(UserInfoParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        UserDTO userDTO = buildUserRegisterInfo(request);
        return userDTO;
    }

    /**
     *
     * @param request
     * @return cloud.xlh.domin.dto.UserDTO
     * @author XuLeHuang
     * @create 2023/1/18
     * @name: 构建用户注册信息
     * @Description:
     **/
    public UserDTO buildUserRegisterInfo(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String ipAddress = CommonUtil.getIpAddress(request);
        String browser = IpUtil.getBrowser(request);
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String age = request.getParameter("age");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String createTime = request.getParameter("createTime");
        String updateTime = request.getParameter("updateTime");
        String status = request.getParameter("status");
        UserDTO userDTO = new UserDTO();
        userDTO.setName(name)
                .setPassword(password)
                .setSex(sex)
                .setAge(age)
                .setEmail(email)
                .setPhone(phone)
                .setAddress(address)
                .setCreateTime(createTime)
                .setUpdateTime(updateTime)
                .setStatus(status)
                .setIpAddress(ipAddress)
                .setBrowser(browser);
        return userDTO;
    }
}
